package com.healthy.util;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author Maple.Chen
 * @Description 文件上传的工具
 * @Date 17:20 2020/5/21
 **/
public class FileUtil {

    /*
    判断文件或路径是否存在，不存在即创建
     */
    public static boolean createFileOrPath(HttpServletRequest request, String relativePath) {
        File dirOrFile = new File(request.getServletContext().getRealPath(File.separator) + relativePath);
        if (!dirOrFile.exists())
            dirOrFile.mkdirs();
        return true;
    }

    /*
    删除文件，有则删除，无则不操作
     */
    public static boolean deleteFile(String fileAndPath) {
        File file = new File(fileAndPath);
        if (file.exists())
            file.delete();
        return true;
    }

    /*
    由文件名解析出文件的扩展名
     */
    public static String getFileNameEnds(String fileFullName) {
        int lastIdx = fileFullName.lastIndexOf(".");
        if (lastIdx < 1) {
            return "";
        } else {
            return fileFullName.substring(lastIdx);
        }
    }

    /*
    由文件名解析出文件名，不含扩展名
     */
    public static String getFileNameExcludingEnds(String fileFullName) {
        int lastIdx = fileFullName.lastIndexOf(".");
        if (lastIdx < 1) {
            return fileFullName;
        } else {
            return fileFullName.substring(0, lastIdx);
        }
    }

    /*
    上传的文件保存
     */
    public static boolean saveFile(MultipartFile file, String saveToPath) {
        try {
            file.transferTo(new File(saveToPath));
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    
    /*
   文件的下载
     */
    public ResponseEntity<byte[]> downloadFile(HttpServletRequest request, String filePath) throws IOException{
    	request.setCharacterEncoding("UTF-8");
		
		//获取文件
    	File file = new File(request.getServletContext().getRealPath("/") + filePath);
		
		//获取文件名
		String fileName = file.getName();
		
		//解决文件名乱码
		String fileName1 =new String(fileName.getBytes("UTF-8"),"iso-8859-1");
	   
		//读取二进制文件
		byte[] body = null;
	    InputStream is = new FileInputStream(file);
	    body = new byte[is.available()];
	    is.read(body);
	    HttpHeaders headers = new HttpHeaders();
	    
	    //通知浏览器以attachment（下载方式）打开图片
	    headers.add("Content-Disposition", "attchement;filename=" + fileName1);
	    
	    //application/octet-stream二进制流数据（最常见的文件下载）。
	    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	    
	    //文件下载的Http协议中的状态最好使用HttpStatus.OK。
	    HttpStatus statusCode = HttpStatus.OK;	    
	    ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);	    
	    
	    return entity;
    }
}
